package com.itlong.cloud.controller.parking;

import com.google.zxing.BarcodeFormat;
import com.itlong.cloud.POJO.DTO.property.PropertyParkCouponGetPageDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyParkCouponSaveDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyParkCouponUpdateDTO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.PO.PropertyParkCouponPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyParkCouponExportVO;
import com.itlong.cloud.POJO.VO.property.PropertyParkCouponGetOneVO;
import com.itlong.cloud.POJO.VO.property.PropertyParkCouponGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.noncore.property.IPropertyParkCouponServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.picture.QrcodeUtils;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      智慧停车-停车优惠券管理
 * </desc>
 *
 * @createDate 2018/11/06
 */
@RestController
@RequestMapping("/parking/coupon")
@RefreshScope
public class PropertyParkCouponController extends BaseController {

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Value("${" + PlatformConstants.PARK_COUPON_HTML_SERVERPATH + "}")
    public String PARK_COUPON_HTML_SERVERPATH;

    @Autowired
    private IPropertyParkCouponServiceClient iPropertyParkCouponServiceClient;

    @Autowired
    private IOperateProjectServiceClient iOperateProjectServiceClient;

    /**
     * <desc>
     *      获取单个优惠券信息
     * </desc>
     *
     * @param parkCouponId 优惠券id
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/06
     */
    @ResponseBody
    @PostMapping("getOne")
    public Object getOneCoupon(String parkCouponId){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            parkCouponId = request.getAttribute("parkCouponId") == null ? null : request.getAttribute("parkCouponId").toString();
            if (StringUtils.isBlank(parkCouponId)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            PropertyParkCouponGetOneVO propertyParkCouponGetOneVO = iPropertyParkCouponServiceClient.getOneCoupon(parkCouponId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyParkCouponGetOneVO);
        } catch (Exception e) {
            throw new DataAccessException("【物业-智慧停车】查询单条优惠券信息失败",e);
        }
    }

    /**
     * <desc>
     *      分页获取优惠券
     * </desc>
     *
     * @param propertyParkCouponGetPageDTO 分页获取优惠券DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/06
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getPage")
    public Object getCouponPage(PropertyParkCouponGetPageDTO propertyParkCouponGetPageDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyParkCouponGetPageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyParkCouponGetPageDTO.class, request);
            if (propertyParkCouponGetPageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyParkCouponGetPageDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            Page<PropertyParkCouponGetPageVO> parkCouponGetPageVOPage = iPropertyParkCouponServiceClient.getCouponPage(propertyParkCouponGetPageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),parkCouponGetPageVOPage);
        } catch (Exception e) {
            throw new DataAccessException("【物业-智慧停车】分页获取优惠券信息失败",e);
        }
    }

    /**
     * <desc>
     *      生成优惠券
     * </desc>
     *
     * @param propertyParkCouponSaveDTO 生成优惠券DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/06
     */
    @ResponseBody
    @PostMapping("save")
    @LoggerInfo(operateDesc = LogDescConstant.PARKING_COUPON_SAVE_LOG_DESC)
    @AuthAccessRequired
    public Object saveCoupon(PropertyParkCouponSaveDTO propertyParkCouponSaveDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyParkCouponSaveDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyParkCouponSaveDTO.class, request);
            if (propertyParkCouponSaveDTO == null || StringUtils.isBlank(propertyParkCouponSaveDTO.getDerate()) || propertyParkCouponSaveDTO.getCount() == null
                    || StringUtils.isBlank(propertyParkCouponSaveDTO.getEndTime())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyParkCouponSaveDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(propertyParkCouponSaveDTO.getType(), 1, 2)) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_TYPE_ERR.getErrorCode());
            }
            if (propertyParkCouponSaveDTO.getType() == 1 && !propertyParkCouponSaveDTO.getDerate().matches("^([0-9])(\\.\\d{1})?$")) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            if (propertyParkCouponSaveDTO.getType() == 2 && !propertyParkCouponSaveDTO.getDerate().matches("^([1-9][0-9]{0,2})?$")) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            Date endTime = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1).parse(propertyParkCouponSaveDTO.getEndTime());
            if (endTime.compareTo(new Date()) <= 0) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_END_TIME_ERR.getErrorCode());
            }
            // 单次创建不能超过200条
            if (propertyParkCouponSaveDTO.getCount() > 200) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_COUNT_ERR.getErrorCode());
            }
            // 单项目未使用的优惠券总计不能超过10000条
            Integer count = iPropertyParkCouponServiceClient.getAvailableCouponCount(propertyParkCouponSaveDTO.getProjectId());
            if (count + propertyParkCouponSaveDTO.getCount() > 10000) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_OVERFLOW_ERR.getErrorCode());
            }
            List<PropertyParkCouponPO> propertyParkCouponPOList = iPropertyParkCouponServiceClient.saveCoupon(propertyParkCouponSaveDTO);
            if (propertyParkCouponSaveDTO.getExport() != null && propertyParkCouponSaveDTO.getExport().equals(1)) {
                // 同时导出添加的优惠券,将逗号相连的id字符串数据返回给前端，前端进行请求导出接口渲染成网页
//                ProjectPO oneProject = iOperateProjectServiceClient.getOneProject(propertyParkCouponSaveDTO.getProjectId());
//                List<PropertyParkCouponExportVO> propertyParkCouponExportVOList = new ArrayList<>();
                StringBuilder ids = new StringBuilder();
                for (PropertyParkCouponPO propertyParkCouponPO : propertyParkCouponPOList){
//                    PropertyParkCouponExportVO propertyParkCouponExportVO = new PropertyParkCouponExportVO();
//                    propertyParkCouponExportVO.setParkName(oneProject.getProjectName() + "停车场");
//                    propertyParkCouponExportVO.setType(propertyParkCouponSaveDTO.getType());
//                    propertyParkCouponExportVO.setDerate(propertyParkCouponSaveDTO.getDerate());
//                    propertyParkCouponExportVO.setRedeemCode(propertyParkCouponPO.getRedeemCode());
//                    propertyParkCouponExportVO.setEndTime(propertyParkCouponSaveDTO.getEndTime());
//                    // 二维码的内容
//                    String htmlUrl = PARK_COUPON_HTML_SERVERPATH + "?redeemCode=" + propertyParkCouponPO.getRedeemCode();
//                    // 生成二维码
//                    ByteArrayOutputStream os = new ByteArrayOutputStream();
//                    BufferedImage bim = QrcodeUtils.getQR_CODEBufferedImage(htmlUrl, BarcodeFormat.QR_CODE, 300, 300, QrcodeUtils.getDecodeHintType());
//                    ImageIO.write(bim, "jpg", os);
//                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(os.toByteArray());
//                    String qrCodeUrl = this.uploadFile(byteArrayInputStream);
//                    propertyParkCouponExportVO.setQrcodeUrl(qrCodeUrl);
//                    propertyParkCouponExportVOList.add(propertyParkCouponExportVO);
                    if (ids.length() == 0) {
                        ids.append(propertyParkCouponPO.getParkCouponId());
                    } else {
                        ids.append(",").append(propertyParkCouponPO.getParkCouponId());
                    }
                }
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),ids);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业-智慧停车】生成优惠券失败",e);
        }
    }

    /**
     * <desc>
     *      修改优惠券
     * </desc>
     *
     * @param propertyParkCouponUpdateDTO 修改优惠券DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/07
     */
    @ResponseBody
    @PostMapping("update")
    @LoggerInfo(operateDesc = LogDescConstant.PARKING_COUPON_UPDATE_LOG_DESC)
    @AuthAccessRequired
    public Object updateCoupon(PropertyParkCouponUpdateDTO propertyParkCouponUpdateDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyParkCouponUpdateDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyParkCouponUpdateDTO.class, request);
            if (propertyParkCouponUpdateDTO == null || StringUtils.isBlank(propertyParkCouponUpdateDTO.getDerate()) || StringUtils.isBlank(propertyParkCouponUpdateDTO.getEndTime())
                    || StringUtils.isBlank(propertyParkCouponUpdateDTO.getParkCouponId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyParkCouponUpdateDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(propertyParkCouponUpdateDTO.getType(), 1, 2)) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_TYPE_ERR.getErrorCode());
            }
            if (propertyParkCouponUpdateDTO.getType() == 1 && !propertyParkCouponUpdateDTO.getDerate().matches("^([0-9])(\\.\\d{1})?$")) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            if (propertyParkCouponUpdateDTO.getType() == 2 && !propertyParkCouponUpdateDTO.getDerate().matches("^([1-9][0-9]{0,2})?$")) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            Date endTime = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1).parse(propertyParkCouponUpdateDTO.getEndTime());
            if (endTime.compareTo(new Date()) <= 0) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_END_TIME_ERR.getErrorCode());
            }
            PropertyParkCouponGetPageDTO propertyParkCouponGetPageDTO = new PropertyParkCouponGetPageDTO();
            propertyParkCouponGetPageDTO.setIds(propertyParkCouponUpdateDTO.getParkCouponId());
            List<PropertyParkCouponGetPageVO> propertyParkCouponGetPageVOList = iPropertyParkCouponServiceClient.getExportData(propertyParkCouponGetPageDTO);
            for (PropertyParkCouponGetPageVO propertyParkCouponGetPageVO : propertyParkCouponGetPageVOList){
                if (propertyParkCouponGetPageVO.getRedeemStatus() == 2 || propertyParkCouponGetPageVO.getUseStatus() == 2) {
                    return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_ALREADY_USE_ERR.getErrorCode());
                }
            }
            iPropertyParkCouponServiceClient.updateCoupon(propertyParkCouponUpdateDTO);
            return new MessageVO(propertyParkCouponUpdateDTO.getParkCouponId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业-智慧停车】修改优惠券失败",e);
        }
    }

    /**
     * <desc>
     *      删除优惠券
     * </desc>
     *
     * @param propertyParkCouponGetPageDTO 查询参数
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/07
     */
    @ResponseBody
    @PostMapping("delete")
    @LoggerInfo(operateDesc = LogDescConstant.PARKING_COUPON_DELETE_LOG_DESC)
    @AuthAccessRequired
    public Object deleteCoupons(PropertyParkCouponGetPageDTO propertyParkCouponGetPageDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyParkCouponGetPageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyParkCouponGetPageDTO.class, request);
            if (propertyParkCouponGetPageDTO == null || StringUtils.isBlank(propertyParkCouponGetPageDTO.getIds())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            List<PropertyParkCouponGetPageVO> propertyParkCouponGetPageVOList = iPropertyParkCouponServiceClient.getExportData(propertyParkCouponGetPageDTO);
            Integer count = 0;
            for (PropertyParkCouponGetPageVO propertyParkCouponGetPageVO : propertyParkCouponGetPageVOList) {
                if (propertyParkCouponGetPageVO.getRedeemStatus() == 2) {
                    count++;
                }
            }
            if (count > 0) {
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),count);
            }
            iPropertyParkCouponServiceClient.deleteCoupons(propertyParkCouponGetPageDTO.getIds());
            return new MessageVO(propertyParkCouponGetPageDTO.getIds(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业-智慧停车】删除优惠券失败",e);
        }
    }

    /**
     * <desc>
     *      导出优惠券
     * </desc>
     *
     * @param propertyParkCouponGetPageDTO 查询参数
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/07
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("export")
    public Object exportCoupons(PropertyParkCouponGetPageDTO propertyParkCouponGetPageDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyParkCouponGetPageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyParkCouponGetPageDTO.class, request);
            if (propertyParkCouponGetPageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyParkCouponGetPageDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            List<PropertyParkCouponGetPageVO> propertyParkCouponGetPageVOList = iPropertyParkCouponServiceClient.getExportData(propertyParkCouponGetPageDTO);
            if (propertyParkCouponGetPageVOList == null || propertyParkCouponGetPageVOList.size() == 0) {
                return new MessageVO(PropertyErrorCodeEnum.EXPORT_DATA_EMPTY_ERR.getErrorCode());
            }
            if (propertyParkCouponGetPageVOList.size() > 200) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_COUPON_EXPORT_COUNT_ERR.getErrorCode());
            }
//            Integer count = 0;
//            for (PropertyParkCouponGetPageVO propertyParkCouponGetPageVO : propertyParkCouponGetPageVOList){
//                if (propertyParkCouponGetPageVO.getRedeemStatus() == 2) {
//                    count++;
//                }
//            }
//            if (count > 0) {
//                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),count);
//            }
            List<PropertyParkCouponExportVO> propertyParkCouponExportVOList = new ArrayList<>();
            ProjectPO oneProject = iOperateProjectServiceClient.getOneProject(propertyParkCouponGetPageDTO.getProjectId());
            String parkName = oneProject.getProjectName() + "停车场";
            for (PropertyParkCouponGetPageVO propertyParkCouponGetPageVO : propertyParkCouponGetPageVOList) {
                if (propertyParkCouponGetPageVO.getRedeemStatus() == 2 || propertyParkCouponGetPageVO.getUseStatus() == 3) {
                    continue;
                }
                PropertyParkCouponExportVO propertyParkCouponExportVO = new PropertyParkCouponExportVO();
                propertyParkCouponExportVO.setParkName(parkName);
                propertyParkCouponExportVO.setType(propertyParkCouponGetPageVO.getType());
                propertyParkCouponExportVO.setDerate(propertyParkCouponGetPageVO.getDerate());
                propertyParkCouponExportVO.setRedeemCode(propertyParkCouponGetPageVO.getRedeemCode());
                propertyParkCouponExportVO.setEndTime(propertyParkCouponGetPageVO.getEndTime());
                // 二维码的内容
                String htmlUrl = PARK_COUPON_HTML_SERVERPATH + "?redeemCode=" + propertyParkCouponGetPageVO.getRedeemCode();
                // 生成二维码
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                BufferedImage bim = QrcodeUtils.getQR_CODEBufferedImage(htmlUrl, BarcodeFormat.QR_CODE, 300, 300, QrcodeUtils.getDecodeHintType());
                ImageIO.write(bim, "jpg", os);
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(os.toByteArray());
                String qrCodeUrl = this.uploadFile(byteArrayInputStream);
                propertyParkCouponExportVO.setQrcodeUrl(qrCodeUrl);
                propertyParkCouponExportVOList.add(propertyParkCouponExportVO);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyParkCouponExportVOList);
        } catch (Exception e) {
            throw new DataAccessException("【物业-智慧停车】导出优惠券失败",e);
        }
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @return 文件上传成功后会返回Url,否则返回空
     * @author wangzhi
     * @createDate 2018/11/06
     */
    private String uploadFile(InputStream inputStream) throws IOException {
        String fileUrl = "";
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                "jpg",
                FILE_ACCESS_URL,
                FileCatalogEnum.PARK_COUPON_QR_CODE_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

}
